var spiralOrder = function(matrix) {
  const [row, col] = [matrix.length, matrix[0].length];
  const ans = [];

  let left = 0, right = col - 1, top = 0, bottom = row - 1, num = 1;

  while (num <= row * col) {
    for (let i = left; i <= right && num <= row * col; i++) {
      ans.push(matrix[top][i]);
      num++;
    }
    top++;
    for (let i = top; i <= bottom && num <= row * col; i++) {
      ans.push(matrix[i][right]);
      num++;
    }
    right--;
    for (let i = right; i >= left && num <= row * col; i--) {
      ans.push(matrix[bottom][i]);
      num++;
    };
    bottom--;
    for (let i = bottom; i >= top && num <= row * col; i--) {
      ans.push(matrix[i][left]);
      num++;
    }
    left++;
  }

  return ans;
}

const matrix = [[1,2,3],[4,5,6],[7,8,9]];
console.log(spiralOrder(matrix))